<template>
  <div class="filter-criteria" ref="filterRef">
    <div class="titles"> 筛选条件 </div>
    <el-form id="scene-filter-container" class="filter-container">
      <el-form-item>
        <template v-for="(formItem, index) in form" :key="formItem.fieldType + index">
          <el-row class="w-50% mb-8px" v-if="formItem.checked">
            <el-col :span="8">
              <el-select
                class="w-100%"
                v-model="formItem.field"
                disabled
                placeholder="请选择要筛选的字段名"
              >
                <el-option
                  v-for="(item, idx) in fieldList"
                  :key="idx"
                  :label="item.fieldName"
                  :value="item.field"
                />
              </el-select>
            </el-col>

            <el-col :span="1">&nbsp;</el-col>
            <el-col :span="4">
              <el-select
                @change="clearTimeValue(index)"
                v-model="formItem.condition"
                placeholder="请选择条件"
              >
                <el-option
                  v-for="item in formItem.queryTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="1">&nbsp;</el-col>
            <el-col :span="10">
              <!-- select -->
              <template v-if="formItem.fieldType == 'select'">
                <el-select
                  :multiple="formItem.condition == 'in'"
                  v-model="formItem.value"
                  placeholder="请选择筛选条件"
                >
                  <el-option
                    v-for="item in formItem.queryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
              <!-- number -->
              <template v-if="formItem.fieldType == 'number'">
                <!-- 单个 -->
                <el-input-number
                  v-if="formItem.condition != 'between'"
                  class="number-input"
                  v-model="formItem.value"
                  :min="0"
                  controls-position="right"
                />
                <!-- 区间 -->
                <template v-else>
                  <el-input-number
                    :min="0"
                    class="number-input"
                    v-model="betweenNumber"
                    controls-position="right"
                  />
                  -
                  <el-input-number
                    :min="0"
                    v-model="betweenNumber1"
                    class="number-input"
                    controls-position="right"
                  />
                </template>
              </template>
              <!-- time -->
              <template v-if="formItem.fieldType == 'time'">
                <!-- 单个时间 -->
                <el-date-picker
                  v-if="formItem.condition != 'between'"
                  v-model="formItem.value"
                  class="!w-100%"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="date"
                  placeholder="请选择时间"
                  clearable
                />
                <!-- 时间区间 -->
                <template v-else>
                  <el-date-picker
                    v-model="formItem.value"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="!w-360px"
                  />
                </template>
              </template>
              <!-- level -->
              <template v-if="formItem.fieldType == 'level'">
                <el-select
                  :multiple="formItem.condition == 'in'"
                  clearable
                  v-model="formItem.value"
                  placeholder="请选择级别"
                  class="!w-100%"
                >
                  <el-option
                    v-for="dict in resultLevel"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  >
                    <el-tag
                      :disable-transitions="false"
                      :style="{
                        background: dict.bgColor,
                        color: dict.textColor,
                        marginRight: '10px',
                        border: 'none',
                        cursor: 'pointer',
                        paddingRight: '9px'
                      }"
                    >
                      {{ dict.name }}
                    </el-tag>
                  </el-option>
                </el-select>
              </template>
              <!-- label -->
              <template v-if="formItem.fieldType == 'label'">
                <el-select multiple v-model="formItem.value">
                  <template v-for="group in tagList" :key="group.name">
                    <el-option disabled :label="group.name" :value="null" class="group-title" />
                    <el-option
                      v-for="item in group.labelList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <el-tag :style="{ background: item.bgColor, color: item.textColor }">{{
                        item.name
                      }}</el-tag>
                    </el-option>
                  </template>
                </el-select>
              </template>
              <!-- area -->
              <template v-if="formItem.fieldType == 'area'">
                <el-cascader
                  @change="handleChange"
                  ref="cascaderRef"
                  v-model="formItem.value"
                  :options="areaList"
                  :props="defaultPropsCheck"
                  class="!w-260px"
                  clearable
                  style="display: table-footer-group"
                  filterable
                  placeholder="请选择所在地"
                />
              </template>
              <!-- module -->
              <template v-if="formItem.fieldType == 'module'">
                <el-select v-model="formItem.value" placeholder="请选择模块">
                  <el-option
                    v-for="item in modules"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
              <!-- input -->
              <template v-if="formItem.fieldType == 'input'">
                <el-select
                  class="w-90%"
                  v-model="formItem.value"
                  :multiple-limit="20"
                  default-first-option
                  multiple
                  clearable
                  filterable
                  allow-create
                  placeholder="单个词不超过30字符，最多20词，回车键隔开"
                  popper-class="hidden-pop"
                />
              </template>
              <el-input
                v-if="formItem.fieldType == ''"
                v-model="formItem.value"
                placeholder="请选择左侧条件"
              ></el-input>
            </el-col>
          </el-row>
        </template>
      </el-form-item>
    </el-form>
    <p v-if="showErrors" class="el-icon-warning warning-info">
      <span class="desc">筛选条件中有重复项！</span>
    </p>
    <div>
      <el-button type="primary" @click="filterSearch" :disabled="!form">筛选</el-button>
      <el-button @click="clearValue">清空外露筛选值</el-button>
    </div>
  </div>
</template>
<script setup>
import { customFieldHeadList } from '@/api/crm/module/index'
import * as customerTagApi from '@/api/crm/customerTagConfig/index'

const props = defineProps({
  advanceValue: Object,
  modulesId: String,
  moduleOption: Array,
  fieldList: Array,
  tagList: Array
})
const filterRef = ref(null)
const form = ref([])
/**字典*/
const QueryConditions = {
  eq: '等于',
  neq: '不等于',
  in: '包含',
  nin: '不包含',
  gt: '大于',
  gte: '大于等于',
  lt: '小于',
  lte: '小于等于',
  isNull: '空',
  isNotNull: '非空',
  like: '模糊查询',
  between: '范围区间'
}
const fieldMap = {
  crm_clue: 1,
  crm_customer: 1
}
const betweenNumber = ref(0)
const betweenNumber1 = ref(0)
/**获取当前组件的高度*/
const getLabelHeight = () => {
  return filterRef.value.offsetHeight + 16
}
watch(
  () => props.advanceValue,
  (value) => {
    form.value = []
    const obj = value.params
    for (const key in obj) {
      const result = props.fieldList.find((item) => item.field == key)
      let obj2 = {
        field: result.field,
        fieldName: result.fieldName,
        fieldType: result.fieldType,
        queryOptions: result.queryOptions
          ? Object.entries(result.queryOptions).map(([value, label]) => {
              return {
                label: label,
                value: value
              }
            })
          : null,
        queryType: result.queryType,
        queryTypeOption: result.queryType.map((condition) => {
          return {
            label: QueryConditions[condition],
            value: condition
          }
        }),
        condition: obj[key].condition,
        value: null
      }
      if (obj2.fieldType == 'input') {
        if (obj2.condition == 'in') {
          obj2.value = obj[key].value
          obj2.custom = obj[key].custom
          obj2.checked = obj[key].checked
        } else {
          obj2.value = obj[key].value?.split(',')
          obj2.custom = obj[key].custom
          obj2.checked = obj[key].checked
        }
      } else if (obj2.fieldType == 'number') {
        if (obj2.condition != 'between') {
          obj2.value = obj[key].value
          obj2.custom = obj[key].custom
          obj2.checked = obj[key].checked
        } else {
          obj2.custom = obj[key].custom
          betweenNumber.value = obj[key].value[0]
          betweenNumber1.value = obj[key].value[1]
          obj2.checked = obj[key].checked
        }
      } else if (obj2.fieldType == 'area') {
        if (obj2.condition == 'in') {
          obj2.value = Number(obj[key].value.join(','))
          obj2.checked = obj[key].checked
        } else {
          obj2.value = obj[key].value
          obj2.checked = obj[key].checked
        }
      } else if (obj2.fieldType == 'label') {
        if (obj2.condition == 'in') {
          obj2.value = obj[key].value
        } else {
          obj2.value = obj[key].value?.split(',').map(Number)
        }
        obj2.checked = obj[key].checked
      } else {
        obj2.value = obj[key].value
        obj2.custom = obj[key].custom
        obj2.checked = obj[key].checked
      }
      form.value.push(obj2)
    }
  },
  { deep: true, immediate: true }
)

/**区间进行切换清空*/
const clearTimeValue = (index) => {
  if (form.value[index].fieldType == 'time' && form.value[index].condition != 'between') {
    form.value[index].value = 0
  } else if (form.value[index].fieldType == 'time' && form.value[index].condition == 'between') {
    form.value[index].value = []
  } else if (form.value[index].fieldType == 'select' && form.value[index].condition == 'in') {
    form.value[index].value = []
  } else if (form.value[index].fieldType == 'select' && form.value[index].condition != 'in') {
    form.value[index].value = ''
  } else if (form.value[index].fieldType == 'level' && form.value[index].condition == 'in') {
    form.value[index].value = []
  } else if (form.value[index].fieldType == 'level' && form.value[index].condition != 'in') {
    form.value[index].value = ''
  }
}
const emit = defineEmits(['clearAdvanceValue', 'tellHeight', 'searchAdvance'])
// 清空所有值
const clearValue = () => {
  emit('clearAdvanceValue')
}
const isMounted = ref(false)
watch(
  () => form.value,
  (val) => {
    if (val.length && isMounted.value) {
      emit('tellHeight', getLabelHeight())
    }
  },
  { immediate: true, deep: true }
)
onMounted(() => {
  emit('tellHeight', getLabelHeight())
})
const showErrors = computed(() => {
  const result = form.value.some((item, index) => {
    return form.value.findIndex((i) => i.field == item.field) !== index
  })
  return result
})
const filterSearch = async () => {
  if (showErrors.value) {
    return
  }
  const rules3 = form.value.some(
    (item) =>
      item.value === '' ||
      item.value?.length == 0 ||
      (item.value == null && item.fieldType == 'time')
  )
  if (rules3) {
    ElMessage.error('请检查筛选条件!')
    return
  }
  let obj = {
    params: {}
  }
  form.value.map((item) => {
    if (item.fieldType == 'input') {
      if (item.condition == 'in') {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value,
          custom: item.custom,
          checked: item.checked
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value.join(','),
          custom: item.custom,
          checked: item.checked
        }
      }
    } else if (item.fieldType == 'number') {
      if (item.condition != 'between') {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value,
          custom: item.custom,
          checked: item.checked
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: [betweenNumber.value, betweenNumber1.value],
          custom: item.custom,
          checked: item.checked
        }
      }
    } else if (item.fieldType == 'area') {
      if (item.condition == 'in') {
        obj.params[item.field] = {
          condition: item.condition,
          value: [item.value],
          checked: item.checked
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value,
          checked: item.checked
        }
      }
    } else if (item.fieldType == 'label') {
      if (item.condition == 'in') {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value,
          checked: item.checked
        }
      } else {
        obj.params[item.field] = {
          condition: item.condition,
          value: item.value.join(','),
          checked: item.checked
        }
      }
    } else {
      obj.params[item.field] = {
        condition: item.condition,
        value: item.value,
        custom: item.custom,
        checked: item.checked
      }
    }
  })
  emit('searchAdvance', obj)
}
</script>

<style scoped lang="scss">
.titles {
  color: #5e6c84;
  font-size: 14px;
  line-height: 32px;
}
.filter-criteria {
  padding: 20px;
  background-color: #fff;
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 8px #172b4d1a;
}
</style>
